"""
Case Type   : HTAP行列融合特性
Case Name   : 部分列转换后插入数据，验证查询数据正确
Create At   : 2025/1/8
Owner       : ningyali
Description :
    1.建表进行行列转换
    2.查询query_imcstore_views
    3.再次插入数据
    4.查询query_imcstore_views
    5.开启enable_imcsscan，explain和查询
    6.关闭enable_imcsscan，explain和查询
    7.清理数据环境
Expect      :
    1.执行成功
    2.执行成功
    3.执行成功
    4.执行成功，cu_num_in_mem+cu_num_in_disk增大
    5.执行成功, 查询计划走imcs scan
    6.执行成功，查询计划不走imcs scan,查询结果与第三步一致
    7.执行成功
History     :
"""

import os
import unittest

from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger
from yat.test import macro


class HTAP(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        self.pri_sh = CommonSH('SingleDbUser')
        self.Constant = Constant()
        self.common = Common()
        self.t_name = 't_htap_single_0133'

    def test_trans(self):
        text = '----step1:建表进行行列转换; expect:执行成功----'
        self.log.info(text)
        sql = f'drop table if exists {self.t_name};' \
              f'create table {self.t_name}(' \
              f'    c1 integer,' \
              f'    c2 varchar(30),' \
              f'    c3 char(30));' \
              f'insert into {self.t_name} values (' \
              f'generate_series(1, 100000),' \
              f'generate_series(1, 100000)||\'aaa\',' \
              f'generate_series(1, 100000)||\'bbb\');' \
              f'alter table {self.t_name} imcstored(c1,c3,c3,c1);'
        sql_res = self.pri_sh.execut_db_sql(
            sql, env_path=macro.SINGLE_DB_ENV_PATH)
        expect_res = r'CREATE TABLE\s+INSERT 0 100000\s+ALTER TABLE'
        self.assertRegex(sql_res, expect_res, f'执行失败:{text}')

        text = '----step2:查询query_imcstore_views; expect:执行成功----'
        self.log.info(text)
        q_sql = f'select *,cu_num_in_mem+cu_num_in_disk as all_num ' \
                f'from query_imcstore_views() ' \
                f'where relname like \'{self.t_name}%\' order by relname;'
        q_res1 = self.pri_sh.execut_db_sql(
            q_sql, env_path=macro.SINGLE_DB_ENV_PATH)
        q_rows1, _ = self.common.parse_sql_query_res(q_res1)

        text = '----step3:插入数据; expect:执行成功----'
        self.log.info(text)
        sql = f'insert into {self.t_name} values (' \
              f'generate_series(100000, 200000),' \
              f'generate_series(100000, 200000)||\'aaa\',' \
              f'generate_series(100000, 200000)||\'bbb\');' \
              f'\\d+'
        sql_res = self.pri_sh.execut_db_sql(
            sql, env_path=macro.SINGLE_DB_ENV_PATH)
        self.assertIn('INSERT 0 100001', sql_res, f'执行失败:{text}')

        text = '----step4:查询query_imcstore_views; ' \
               'expect:执行成功，cu_num_in_mem+cu_num_in_disk增大----'
        self.log.info(text)
        q_res2 = self.pri_sh.execut_db_sql(
            q_sql, env_path=macro.SINGLE_DB_ENV_PATH)
        q_rows2, _ = self.common.parse_sql_query_res(q_res2)
        self.assertGreater(q_rows2[0][-1], q_rows1[0][-1], f'执行失败:{text}')

        text = '----step5:开启enable_imcsscan，explain和查询; ' \
               'expect:执行成功, 查询计划走imcs scan----'
        self.log.info(text)
        sql = f'set enable_imcsscan to on;' \
              f'explain (costs false) select c3,c1 from {self.t_name} ' \
              f'where c1%2=0 order by c1 desc limit 10;' \
              f'select c3,c1 from {self.t_name} ' \
              f'where c1%2=0 order by c1 desc limit 10;'
        sql_res1 = self.pri_sh.execut_db_sql(
            sql, env_path=macro.SINGLE_DB_ENV_PATH)
        rows1, _ = self.common.parse_sql_query_res(sql_res1)
        expect = [['200000bbb', '200000'], ['199998bbb', '199998'],
                  ['199996bbb', '199996'], ['199994bbb', '199994'],
                  ['199992bbb', '199992'], ['199990bbb', '199990'],
                  ['199988bbb', '199988'], ['199986bbb', '199986'],
                  ['199984bbb', '199984'], ['199982bbb', '199982']]
        self.assertIn('IMCStore Scan', sql_res1, f'执行失败:{text}')
        self.assertEqual(expect, rows1[-10:], f'执行失败:{text}')

        text = '----step6:关闭enable_imcsscan，explain和查询; ' \
               'expect:执行成功，查询计划不走imcs scan,查询结果与第三步一致----'
        self.log.info(text)
        sql = f'set enable_imcsscan to off;' \
              f'explain (costs false) select c3,c1 from {self.t_name} ' \
              f'where c1%2=0 order by c1 desc limit 10;' \
              f'select c3,c1 from {self.t_name} ' \
              f'where c1%2=0 order by c1 desc limit 10;'
        sql_res2 = self.pri_sh.execut_db_sql(
            sql, env_path=macro.SINGLE_DB_ENV_PATH)
        rows2, _ = self.common.parse_sql_query_res(sql_res2)
        self.assertNotIn('IMCStore Scan', sql_res2, f'执行失败:{text}')
        self.assertEqual(rows1[-10:], rows2[-10:], f'执行失败:{text}')

    def tearDown(self):
        text = '----step7:清理环境;expect:执行成功----'
        self.log.info(text)
        sql = f'drop table if exists {self.t_name};'
        sql_res = self.pri_sh.execut_db_sql(
            sql, env_path=macro.SINGLE_DB_ENV_PATH)
        self.assertIn('DROP TABLE', sql_res, f'删除表失败:{text}')
        self.log.info(f'-----{os.path.basename(__file__)} end-----')
